package com.xinyu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinyu.domain.Daily;
import com.xinyu.domain.Task;
import com.xinyu.domain.TaskStateHistory;
import com.xinyu.notification.TaskStatusChangePublisher;
import com.xinyu.service.IDailyService;
import com.xinyu.service.ITaskService;
import com.xinyu.service.TaskStateHistoryService;
import com.xinyu.utils.JWTUtils;
import com.xinyu.vo.BaseResult;
import com.xinyu.vo.TaskRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 *  任务
 * </p>
 *
 * @author: XinYu
 * @since 2025-02-17
 */
@RestController
@RequestMapping("/task")
public class TaskController {

    @Autowired
    private ITaskService taskService;

    @Autowired
    private IDailyService dailyService;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private TaskStateHistoryService taskStateHistoryService;

    @Autowired
    private TaskStatusChangePublisher taskStatusChangePublisher;

    @PostMapping("queryByCondition")
    public ResponseEntity<BaseResult> queryByCondition(@RequestBody TaskRequest taskRequest){
        BaseResult br = taskService.queryByCondition(taskRequest);
        return ResponseEntity.ok(br);
    }

    @GetMapping("queryAll")
    public ResponseEntity<BaseResult> queryAll(){
        List<Task> list = taskService.list();
        return ResponseEntity.ok(BaseResult.ok(list));
    }

    @PostMapping("save")
    public ResponseEntity<BaseResult> save(@RequestBody Task task){
        // 1 当前登录用户的id
        String token = request.getHeader("Authorization");
        Integer userIdFromToken = JWTUtils.getUserIdFromToken(token);

        //2 设置发布时间-当前系统时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化时间（可选）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        //3 定义变量
        Daily daily = resolveRelatedDaily(task);
        if (daily == null) {
            return ResponseEntity.ok(BaseResult.error("未找到关联的问题记录"));
        }
        String reason;

        if (task.getId()!=null&&task.getId()>0){
            //更新Daily
            daily.setTaskId(task.getId());//设置任务id
            daily.setState(task.getState());//状态跟任务同步
            daily.setTask(1);//通过这个状态转为任务，0 非任务  1 任务
            dailyService.updateById(daily); // 更新每一条记录
            //更新状态
            Task dbTask = taskService.getById(task.getId());
            reason = "问题"+daily.getId()+":<a target='blank' href='daily-detail/"+daily.getId()+"'>"+daily.getTitle()+"</a>关联了任务"+task.getId();
            if (dbTask.getState()!=task.getState() || !dbTask.getStateReason().equals(task.getStateReason())){
                reason += "," + task.getStateReason();
            }
            task.setStateReason(reason);
            taskService.updateById(task);
            taskStatusChangePublisher.publish(task, dbTask, daily, userIdFromToken, reason);
        }else{
            // 1 当前登录用户的id
            task.setPublishUserId(userIdFromToken);

            //2 设置发布时间-当前系统时间
            task.setPublishTime(formattedDateTime);
            task.setState(1);
            taskService.save(task);
            //更新Daily
            daily.setTaskId(task.getId());
            daily.setTask(1);
            dailyService.updateById(daily);
            //更新状态历史
            reason = "问题"+daily.getId()+":<a  target='blank'  href='daily-detail/'"+daily.getId()+">"+daily.getTitle()+"</a>转为任务"+task.getId();
        }
        //更新状态历史
        TaskStateHistory tsh = new TaskStateHistory(task.getId(),task.getState(),reason,userIdFromToken,formattedDateTime);
        taskStateHistoryService.save(tsh);
        taskService.syncDailyState(task);
        return ResponseEntity.ok(BaseResult.ok());
    }


    @PostMapping("update")
    public ResponseEntity<BaseResult> update(@RequestBody Task task){
        // 设置发布时间-当前系统时间
        LocalDateTime now = LocalDateTime.now();
        // 格式化时间（可选）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = now.format(formatter);

        String token = request.getHeader("Authorization");
        Integer userIdFromToken = JWTUtils.getUserIdFromToken(token);

        Daily daily = resolveRelatedDaily(task);
        if (daily == null) {
            return ResponseEntity.ok(BaseResult.error("未找到关联的问题记录"));
        }

        if (task.getState() ==3 || task.getState() ==4){
            task.setCompletedTime(formattedDateTime);
        }
        Task dbTask = taskService.getById(task.getId());
        String reason = "更新任务状态";
        if (dbTask.getState()!=task.getState() || !dbTask.getStateReason().equals(task.getStateReason())){
            reason += "," + task.getStateReason();
        }
        task.setStateReason(reason);
        taskService.updateById(task);

        //更新状态历史
        TaskStateHistory tsh = new TaskStateHistory(task.getId(),task.getState(),reason,userIdFromToken,formattedDateTime);
        taskStateHistoryService.save(tsh);
        taskService.syncDailyState(task);
        taskStatusChangePublisher.publish(task, dbTask, daily, userIdFromToken, reason);
        return ResponseEntity.ok(BaseResult.ok());
    }
    @GetMapping("{dailyId}")
    public ResponseEntity<BaseResult> findById(@PathVariable Integer dailyId){
        Task task = taskService.findByDailyId(dailyId);
        return ResponseEntity.ok(BaseResult.ok(task));
    }

    @GetMapping("task/{taskId}")
    public ResponseEntity<BaseResult> findByTaskId(@PathVariable Integer taskId){
        Task task = taskService.getById(taskId);
        return ResponseEntity.ok(BaseResult.ok(task));
    }

    private Daily resolveRelatedDaily(Task task) {
        Daily daily = null;
        if (task.getDailyId() != null) {
            daily = dailyService.getById(task.getDailyId());
        }
        if (daily == null && task.getId() != null) {
            LambdaQueryWrapper<Daily> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Daily::getTaskId, task.getId());
            daily = dailyService.getOne(wrapper);
        }
        return daily;
    }

}
